<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Message;

class MessageController extends Controller
{
    //

    public function create(Request $request)
    {
        $jsonData['status'] = 200;
        $jsonData['message'] = '短信添加成功';
        $data = $request->all();
        $Message = Message::create($data);
        if ($Message) {
            $jsonData['data'] = $Message->toArray();
        } else {
            $jsonData['status'] = 300;
            $jsonData['message'] = '短信添加失败';
        }
        return response()->json($jsonData);
    }

    public function delete($id)
    {
        $jsonData['status'] = 200;
        $jsonData['message'] = '短信删除成功！';
        $Message = Message::find($id);
        if ($Message) {
            if (!$Message->delete()) {
                $jsonData['status'] = 300;
                $jsonData['message'] = '删除失败';
            }
        } else {
            $jsonData['status'] = 404;
            $jsonData['message'] = '不存在此条记录';
        }
        return response()->json($jsonData);
    }

    public function all(Request $request, $page, $limit)
    {
        $jsonData['status'] = 200;
        $jsonData['message'] = '查询成功！';
        $limit = $limit > 100 ? 100 : $limit;
        --$page;
        $page = $page < 0 ? 0 : $page;
        $offset = $page * $limit;
        $jsonData['data'] = Message::offset($offset)->limit($limit)->get()->toArray();
        $jsonData['total'] = Message::all()->count();
        return response()->json($jsonData);
    }

    public function show(Request $request, $id)
    {
        $jsonData['status'] = 200;
        $jsonData['message'] = '查询成功！';
        $Message = Message::find($id);
        if ($Message) {
            $jsonData['data'] = $Message->toArray();
        } else {
            $jsonData['status'] = 404;
            $jsonData['message'] = '不存在此记录！';
        }
        return response()->json($jsonData);
    }

}
